package cn.kennylee.codehub.springmvc.exceptionhandler;

import jakarta.annotation.PostConstruct;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.internal.engine.path.PathImpl;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.core.Ordered;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.util.Set;

/**
 * <p> spring mvc web常规异常处理 </p>
 * <p>Created on 2025/7/21.</p>
 *
 * @author kennylee
 * @since 0.0.1
 */
@RestControllerAdvice
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@Slf4j
public class WebExceptionHandler implements Ordered {

    private final ExceptionResultFactory exceptionResultFactory;

    public WebExceptionHandler(ExceptionResultFactory exceptionResultFactory) {
        this.exceptionResultFactory = exceptionResultFactory;
    }

    @PostConstruct
    public void init() {
        log.info("Web异常处理类已初始化");
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResultModel<Object> handleError(MissingServletRequestParameterException exception) {
        log.debug("请求参数缺失异常", exception);
        String message = String.format("缺少必要的请求参数: %s", exception.getParameterName());
        return exceptionResultFactory.createFailedResult(ResultErrorCode.PARAM_MISS, message);
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResultModel<Object> handleError(IllegalArgumentException exception) {
        log.debug("参数非法异常", exception);
        String message = String.format("参数非法异常: %s", exception.getMessage());
        return exceptionResultFactory.createFailedResult(ResultErrorCode.PARAM_ILLEGAL_ERROR, message);
    }

    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public ResultModel<Object> handleError(MethodArgumentTypeMismatchException e) {
        log.debug("请求参数类型不匹配异常", e);
        String message = String.format("请求参数格式错误: %s", e.getName());
        return exceptionResultFactory.createFailedResult(ResultErrorCode.PARAM_TYPE_ERROR, message);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultModel<Object> handleError(MethodArgumentNotValidException e) {
        log.debug("参数校验未通过异常", e);
        return handleErrorWithoutParamName(e.getBindingResult());
    }

    @ExceptionHandler(BindException.class)
    public ResultModel<Object> handleError(BindException e) {
        log.debug("参数绑定异常", e);
        return handleError(e.getBindingResult());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public ResultModel<Object> handleError(ConstraintViolationException e) {
        log.debug("参数约束违反异常", e);
        return handleError(e.getConstraintViolations());
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResultModel<Object> handleError(HttpMessageNotReadableException e) {
        log.debug("HTTP消息不可读异常", e);
        return exceptionResultFactory.createFailedResult(ResultErrorCode.MSG_NOT_READABLE);
    }

    protected ResultModel<Object> handleError(BindingResult result) {
        FieldError error = result.getFieldError();
        if (error == null) {
            return exceptionResultFactory.createFailedResult(ResultErrorCode.PARAM_BIND_ERROR);
        }
        String message = String.format("%s:%s", error.getField(), error.getDefaultMessage());
        return exceptionResultFactory.createFailedResult(ResultErrorCode.PARAM_BIND_ERROR, message);
    }

    protected ResultModel<Object> handleErrorWithoutParamName(BindingResult result) {
        FieldError error = result.getFieldError();
        if (error == null) {
            return exceptionResultFactory.createFailedResult(ResultErrorCode.PARAM_BIND_ERROR);
        }
        String message = String.format("%s", error.getDefaultMessage());
        return exceptionResultFactory.createFailedResult(ResultErrorCode.PARAM_BIND_ERROR, message);
    }

    protected ResultModel<Object> handleError(Set<ConstraintViolation<?>> violations) {
        ConstraintViolation<?> violation = violations.iterator().next();
        String path = ((PathImpl) violation.getPropertyPath()).getLeafNode().getName();
        String message = String.format("%s:%s", path, violation.getMessage());
        return exceptionResultFactory.createFailedResult(ResultErrorCode.PARAM_VALID_ERROR, message);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
